<template>
  <div>
    <a-card class="card" :bordered="false" :style="`min-height: ${cardMinHeight}px;`">

      <!--弹窗0 新增按钮-->
      <a-modal
          destroyOnClose
          class="addModal"
          v-model='addModal'
          width='1250px'
          :title="isAdd?'新增':title"
          @ok="handleCancel0"
          @cancel="handleCancel0"
          :bodyStyle="bodyStyle"

      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 250px;display: flex;flex-direction: row;padding: 10px 24px 0px 24px;">
            <a-table
                :columns="key1Columns"
                :data-source="key1Data"
                style="width: 100%;"
                :pagination="key1Pagination"
                @change="onChangeKey1"
                :showPagination="true"
                :loading="addLoading"
                :rowKey="(record1) => {return record1.index}"
                :scroll="{x:true,y: 300 }"
            >
              <template slot="action" slot-scope="record">
                <div v-if="record.status===0">
                  <a v-auth="`update`" @click="addDetail(record)" >编辑</a>
                </div>
              </template>
            </a-table>
          </div>
        </a-spin>

      </a-modal>

      <!--新增详情-->
      <a-modal
          destroyOnClose
          v-model='addDetailModel'
          width='1400px'
          :title="isAdd?'新增详情':title"
          @ok="submitDetail"
          @cancel="handleCancelDetail"
          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 250px;display: flex;flex-direction: row;padding: 10px 24px 0px 24px;">
            <a-table
                :columns="key1ColumnsDetail"
                :data-source="key1DataDetail"
                style="width: 100%;"
                :pagination="key1DetailPagination"
                @change="onChangeKey1Detail"
                :showPagination="true"
                :loading="tableLoadingDetail"
                :rowKey="(record1) => {return record1.index}"
                :scroll="{x:true,y: 300 }"
            >
              <template slot="action0" slot-scope="record0">
                <a-input style='width: 100px;height: 32px' v-model='record0.real_value'  v-auth="`query`"></a-input>
              </template>
              <template slot="action1" slot-scope="record1">
                <a-input style='width: 100px;height: 32px' v-model='record1.method'  v-auth="`query`"></a-input>
              </template>
              <template slot="action2" slot-scope="record2">
                <a-input style='width: 100px;height: 32px' v-model='record2.info_real_cost_time'  v-auth="`query`"></a-input>
              </template>
              <template slot="action3" slot-scope="record3">
                <a-input style='width: 150px;height: 32px' v-model='record3.result'  v-auth="`query`"></a-input>
              </template>
            </a-table>
          </div>
        </a-spin>

      </a-modal>

      <!--详情-->
      <a-modal
          destroyOnClose
          v-model='detailModal'
          width='800px'
          :title="canBeQuery?'详情':title"
          :bodyStyle="bodyStyle"
          @cancel="detailCancel"
          @ok="detailCancel"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 30px;display: flex;flex-direction: row;padding: 10px 24px 10px 24px;justify-content: space-between">
            <div style="width: 95%;">
              <a-form-model   layout="inline" >
                <a-form-model-item
                    label="任务编码"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.code" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="设备"
                    style="margin-left: 66px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.device_name" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="设备编码"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.device_code" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="预计用时"
                    style="margin-left: 38px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.expect_time" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="保养责任人"
                    style="margin-left: 16px">

                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_person_name"
                           :disabled="!canBeEdited || !isAdd"></a-input>

                </a-form-model-item>

                <a-form-model-item
                    label="保养状态"
                    style="margin-left: 38px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_status_name" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>

                <a-form-model-item
                    label="保养时间"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_time" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="保养完成时间"
                    style="margin-left: 10px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.create_time" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="保养类别"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_type_name" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="实际用时"
                    style="margin-left: 38px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.real_cost_time" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="审核状态"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.audit_status" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-divider orientation="left">
                  <span style="font-size: 15px">保养项目</span>
                </a-divider>
                <a-form-model-item
                    label="项目编码"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="getProject.code"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="标准值"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="getProject.standard_value"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="下限值"
                    style="margin-left: 44px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="getProject.lower_limit"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="上限值"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="getProject.upper_limit"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-divider orientation="left">
                  <span style="font-size: 15px">保养结果</span>
                </a-divider>
                <a-form-model-item
                    label="实际值"
                    style="margin-left: 45px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="getResult.real_value"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="方法"
                    style="margin-left: 43px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="getResult.method"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="结果"
                    style="margin-left: 58px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="getResult.result"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>

              </a-form-model>

            </div>
          </div>
        </a-spin>

      </a-modal>

      <!--编辑-->
      <a-modal
          destroyOnClose
          v-model='editModal'
          width='800px'
          :title="canBeQuery?'编辑':title"
          :bodyStyle="bodyStyle"
          @cancel="detailCancel"
          @ok="detailCancel"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 30px;display: flex;flex-direction: row;padding: 10px 24px 10px 24px;justify-content: space-between">
            <div style="width: 95%;">
              <a-form-model   layout="inline" >
                <a-form-model-item
                    label="任务编码"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.code" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="设备"
                    style="margin-left: 66px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.device_name" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="设备编码"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.device_code" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="预计用时"
                    style="margin-left: 38px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.expect_time" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="保养责任人"
                    style="margin-left: 16px">

                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_person_name"
                           :disabled="!canBeEdited || !isAdd"></a-input>

                </a-form-model-item>

                <a-form-model-item
                    label="保养状态"
                    style="margin-left: 38px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_status_name" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>

                <a-form-model-item
                    label="保养时间"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_time" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="保养完成时间"
                    style="margin-left: 10px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.create_time" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="保养类别"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_type_name" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="实际用时"
                    style="margin-left: 38px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.real_cost_time" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="审核状态"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.audit_status" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-divider orientation="left">
                  <span style="font-size: 15px">保养项目</span>
                </a-divider>
                <a-form-model-item
                    label="项目编码"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="getProject.code"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="标准值"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="getProject.standard_value"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="下限值"
                    style="margin-left: 44px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="getProject.lower_limit"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="上限值"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="getProject.upper_limit"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-divider orientation="left">
                  <span style="font-size: 15px">保养结果</span>
                </a-divider>
                <a-form-model-item
                    label="实际值"
                    style="margin-left: 45px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="getResult.real_value"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="方法"
                    style="margin-left: 43px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="getResult.method"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="结果"
                    style="margin-left: 58px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="getResult.result"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>

              </a-form-model>

            </div>
          </div>
        </a-spin>

      </a-modal>

      <page-head-area>
        <div class="extra" style="width: 260px;display: flex;justify-content: space-around">
<!--          <a-badge count="9">-->
            <a-button icon="plus-circle" v-auth="`insert`" @click="add" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">新增</a-button>
<!--          </a-badge>-->
          <a-popconfirm title="确定删除?" @confirm="delMaintenance">
              <a-button icon="delete" v-auth="`delete`" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">删除</a-button>
          </a-popconfirm>

          <a-popconfirm title="确定审核?" @confirm="auditTaskSelect">
            <a-button icon="audit"  style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">审核</a-button>
          </a-popconfirm>

        </div>
      </page-head-area>

      <div class="queryBox">
        <a-form-model layout="inline" :model='queryForm'  class='query' style='display: flex;flex-wrap: wrap;'>
          <a-form-model-item
              label="设备编码"
              style="margin-left: 0px"
          >
            <a-input style='width: 150px;height: 32px' v-model='queryForm.device_code'  v-auth="`query`"></a-input>
          </a-form-model-item>
          <a-form-model-item
              label="设备名称"
          >
            <a-input style='width: 150px;height: 32px' v-model='queryForm.device_name'  v-auth="`query`"></a-input>
          </a-form-model-item>


          <a-form-model-item
              label="保养状态"
          >
            <a-select
                allowClear
                style='width: 150px'
                v-model.trim='queryForm.maintenance_status'
                v-auth="`query`"
            >
              <a-select-option
                  v-for='item in taskStatusList'
                  :key='item.code'
                  :value='item.code'
              >{{item.description}}</a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item
              label="审核状态"
          >
            <a-select
                allowClear
                style='width: 150px'
                v-model.trim='queryForm.audit_status'
                v-auth="`query`"
            >
              <a-select-option
                  v-for='item in taskAuditStatusList'
                  :key='item.code'
                  :value='item.code'
              >{{item.description}}</a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item
              label="日期范围"
          >
            <a-range-picker
                :valueFormat="'YYYY-MM-DD'"
                style="width: 300px;"
                :format="'YYYY-MM-DD'"
                v-model.trim="queryForm.dateSelect"
                :allow-clear="true"/>
          </a-form-model-item>

          <a-form-model-item>
            <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="reset" v-auth="`query`">
              重置
            </a-button>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="filter" v-auth="`query`">
              搜索
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </div>
      <div class="dataBox">
        <a-table
            :columns="columns"
            :data-source="data"
            :pagination="false"
            :loading="tableLoading"
            :rowKey="(recordS) => {return recordS.id}"
            :scroll="{ x: 1000, y: 500 }"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <template slot="action" slot-scope="record">
            <div v-if="record.status===1">
              <a v-auth="`query`" @click="detail(record)">详情</a>
            </div>

            <div v-if="record.status===0">
              <a-popconfirm title="确定已审核?" @confirm="() => auditTask(record)">
                <a v-auth="`update`" >审核</a>
              </a-popconfirm>
              <a-divider type="vertical"/>
              <a v-auth="`update`" @click="edit(record)">编辑</a>
            </div>

          </template>
        </a-table>

      </div>

      <a-pagination
          @change="onChangePage"
          @showSizeChange="showSizeChange"
          :total="pagination.total"
          :showSizeChanger="true"
          :showQuickJumper="true"
          :defaultPageSize="pagination.defaultPageSize"
          :pageSize="pagination.page_size"
          :pageSizeOptions="pagination.pageSizeOptions"
          :current="pagination.current"
          :showTotal="pagination.showTotal"
          style="width: 100%;display: flex;flex-direction: row;justify-content: flex-end;margin-top: 15px"
      ></a-pagination>
    </a-card>
  </div>
</template>

<script>

import {mapGetters} from "vuex";
import PageHeadArea from "../module/pageHeadArea.vue";
import pagination from "ant-design-vue/lib/pagination";
import storage from "store";
import {DEPT_ID, ORGANIZATION_ID, USER_TOKEN} from "@/store/mutation-types";
import axios from "axios";
import moment from "moment";
import {
  file_import, file_upload,
  get_employee_list,
  get_extended_define, get_asset_file_list, get_supplier, get_unit_list, download_file,
  get_organization_list,
  delete_asset, get_asset_list, save_asset, update_asset,
  get_category_type_list, get_organization_profile_list, get_template_list, update_extend
} from "@/services/manage";
import {
  deleteDeviceMaintenanceInfo,
  getCacheById,
  getCurrentUserInfo,
  getDeviceList,
  getDeviceMaintenanceProjectList,
  getDeviceMaintenanceTypeList,
  getDeviceMaintenanceTypeProjectRelationList,
  getMaintenancePlanDeviceRelationList, getRelationByDeviceId,
  getUserNameById,
  listDeviceMaintenanceInfoAll, listDeviceMaintenanceResult,
  listDeviceMaintenanceTaskAll,
  listDeviceMaintenanceTaskByUserId, saveDevice, saveDeviceMaintenanceInfo, saveDeviceMaintenanceResult
} from "../../utils/interface";
import {message} from "ant-design-vue";
import {list_device_maintenance_info_all} from "../../services/deviceMaintenance";
const data = []
const columns = [
  { title: '保养单号', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '设备编码', width: 120, align:'center',dataIndex: 'device_code', key: 'device_code'},
  { title: '设备名称', width: 120, align:'center',dataIndex: 'device_name', key: 'device_name'},
  { title: '保养日期', width: 120, align:'center',dataIndex: 'maintenance_time', key: 'maintenance_time'},
  { title: '保养完成日期', width: 120, align:'center',dataIndex: 'create_time', key: 'create_time'},
  { title: '保养类别', width: 120, align:'center',dataIndex: 'maintenance_type_name', key: 'maintenance_type_name'},
  { title: '实际用时', width: 120, align:'center',dataIndex: 'real_cost_time', key: 'real_cost_time'},
  { title: '计算实际用时', width: 120, align:'center',dataIndex: 'real_cost_time_auto', key: 'real_cost_time_auto'},
  { title: '保养状态', width: 120, align:'center',dataIndex: 'maintenance_status_name', key: 'maintenance_status_name'},
  { title: '保养人', width: 120, align:'center',dataIndex: 'maintenance_person_name', key: 'maintenance_person_name'},
  { title: '预计用时', width: 120, align:'center',dataIndex: 'expect_time', key: 'expect_time'},
  { title: '实际用时', width: 120, align:'center',dataIndex: 'real_cost_time', key: 'real_cost_time'},
  { title: '审核状态', width: 120, align:'center',dataIndex: 'audit_status', key: 'audit_status'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]

const key1Columns = [
  { title: '任务单号', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '设备编码', width: 120, align:'center',dataIndex: 'device_code', key: 'device_code'},
  { title: '设备名称', width: 120, align:'center',dataIndex: 'device_name', key: 'device_name'},
  { title: '保养日期', width: 120, align:'center',dataIndex: 'maintenance_time', key: 'maintenance_time'},
  { title: '保养类别', width: 120, align:'center',dataIndex: 'maintenance_type_name', key: 'maintenance_type_name'},
  { title: '状态', width: 120, align:'center',dataIndex: 'maintenance_status', key: 'maintenance_status'},
  { title: '预计用时', width: 120, align:'center',dataIndex: 'expect_time', key: 'expect_time'},
  { title: '实际用时', width: 120, align:'center',dataIndex: 'real_cost_time', key: 'real_cost_time'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]
const key1ColumnsDetail = [
    { title: '序号', width: 120, align:'center',dataIndex: 'id', key: 'id'},
    { title: '项目编码', width: 120, align:'center',dataIndex: 'code', key: 'code'},
    { title: '项目名称', width: 120, align:'center',dataIndex: 'name', key: 'name'},
    { title: '标准值', width: 120, align:'center',dataIndex: 'standard_value', key: 'standard_value'},
    { title: '单位', width: 120, align:'center',dataIndex: 'unit_name', key: 'unit_name'},
    { title: '上限值', width: 120, align:'center',dataIndex: 'upper_limit', key: 'upper_limit'},
    { title: '下限值', width: 120, align:'center',dataIndex: 'lower_limit', key: 'lower_limit'},
    {
      title: '实际值',
      align:'center',
      key: 'operation',
      fixed: 'right',
      width: 120,
      scopedSlots: { customRender: 'action0' }
    },
    {
      title: '方法',
      align:'center',
      key: 'operation',
      fixed: 'right',
      width: 180,
      scopedSlots: { customRender: 'action1' }
    },
    {
      title: '实际用时',
      align:'center',
      key: 'operation',
      fixed: 'right',
      width: 120,
      scopedSlots: { customRender: 'action2' }
    },

    {
      title: '结果',
      align:'center',
      key: 'operation',
      fixed: 'right',
      width: 180,
      scopedSlots: { customRender: 'action3' }
    }
]
const key1DataDetail=[]


const key1Data =[  ];

export default {
  name: "userAuthority",
  components: {PageHeadArea},
  data() {
    return {
      selectedRowKeys: [],
      getResult:{},
      getProject:{},
      editModal:false,
      record2:{},
      record:{},
      tableLoadingDetail:false,
      key1DataDetail,
      key1ColumnsDetail,
      addLoading:false,
      addDetailModel:false,
      deviceMaintenanceTypeList:[],
      taskStatusList:[
        {code:null,description: '不限'},
        { code: 0, description: "保养中" },
        { code: 1, description: "已完成" },
        { code: 2, description: "视情况而定" }],
      taskAuditStatusList:[
        {code:null,description: '不限'},
        { code: 0, description: "未审核" },
        { code: 1, description: "已审核" }],
      key1Data,
      key1Columns,
      tableLoading01: false,
      axiosSource: null,
      tabKey: '1',
      title:'',
      tabBarGutter: 0,
      tabBarStyle: {
        color: 'rgba(0, 0, 0, 0.85)'
      },
      bodyStyle: {
        'padding': '0px 24px 0px 24px',
        'font-size': '14px',
        'line-height': '1.5',
        'word-wrap': 'break-word',
      },
      cardMinHeight: 0,
      queryForm: {
        device_code: '',
        device_name: '',
        maintenance_status:undefined,
        audit_status:undefined,
        dateSelect:[],
      },
      statusList: [
        // {id: 1, name: '待采购', code: '0', type: 'use_status'},
        {id: 1, name: '正常运行', code: '1',type: 'use_status'},
        {id: 2, name: '不正常运行', code: '2',type: 'use_status'},
      ],
      data,
      columns,
      pagination: {
        total: 0,
        page_size: 10,
        defaultPageSize: 10,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['10', '20', '50', '100', '500'],
      },
      tableLoading: false,
      addModal: false,
      canBeEdited: false, //是否可编辑
      isAdd: false, //是否为新增
      spinning: false,

      detailModal:false, //详情弹窗
      canBeQuery:false, //是否可查询

      remodelModal:false,
      disposalModal:false,
      maintenance_detailsModal:false,
      key1Pagination: {
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      },
      key1DetailPagination:{
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      }
    }
  },
  watch: {},
  authorize: {
    add: 'insert',
    getAssetLedgerList: 'query',
    reset: 'query',
    query: 'query',
    detail: 'query',
    edit: 'update',
    del: 'delete',
    check: 'check',
  },
  computed: {
    ...mapGetters(['getCardMinHeight']),
  },
  created() {
    this.cardMinHeight = this.getCardMinHeight
  },
  async mounted() {
    this.axiosSource = axios.CancelToken.source();
    //保养类别
    await getDeviceMaintenanceTypeList().then(res => {
      this.deviceMaintenanceTypeList = res
    })

    //拿用户信息

    await this.initialize()



  },
  methods: {
    //修改上次保养时间
    async changeLastMaintenanceTime(info_id) {
      let searchInfo = await getRelationByDeviceId({'id':info_id})
      let device_id = searchInfo[0].device_id
      await saveDevice({'id':device_id,'last_maintenance_time':new Date()})

    },
    async auditTaskSelect() {
      for (const it of this.selectedRowKeys) {
        await saveDeviceMaintenanceInfo({'id':it.id,'status':1})
        //修改上次保养时间 last_maintenance_time
        await this.changeLastMaintenanceTime(it.id)
      }
      message.success("审核状态修改成功")
      await this.initialize()
    },
    async auditTask(record) {
      await saveDeviceMaintenanceInfo({'id':record.id,'status':1})
      //修改上次保养时间
      await this.changeLastMaintenanceTime(record.id)
      message.success("审核状态修改成功")
      await this.initialize()
    },
    async submitDetail() {
      this.tableLoadingDetail=true
      // console.log(this.key1DataDetail)
      //submit
      let flag = true;
      for (const it of this.key1DataDetail) {
        if (it.real_value === undefined
            || it.method === ''
            || it.info_real_cost_time === undefined
            || it.result === '') {
          flag = false
          break
        }
      }
      if (flag === false) {
        message.error('请填写完整信息')
      } else {
        let task_id = this.record.id
        let plan_id = this.record.plan_id

        //time->info
        //其他->result
        for (const it of this.key1DataDetail) {
         await saveDeviceMaintenanceInfo({
            'code':it.code,
            'task_id': task_id,
            'plan_id': plan_id,
            'device_id': it.device_id,
            'maintenance_type_id': it.maintenance_type_id,
            'real_cost_time': it.info_real_cost_time,
          })
          // //保存到result
          await saveDeviceMaintenanceResult({
            'task_id': task_id,
            'plan_id': plan_id,
            'device_id': it.device_id,
            'maintenance_project_id': it.id,
            'real_value':it.real_value,
            'method':it.method,
            'result':it.result
          })
          // console.log(it)
        }
        message.success('提交成功')
        this.tableLoadingDetail=false
        this.handleCancelDetail()
        await this.initialize()
      }
    },
    onChangePage (page, pageSize) {
      this.pagination.current = page
      this.pagination.page_size = pageSize
      this.pagination.page = page
      this.initialize()
    },
    showSizeChange(current, size){
      this.pagination.page_size = size
      this.pagination.current = current
      this.pagination.page = current
      this.initialize()
    },
    onSelectChange(selectedRowKeys) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    async addDetail(record) {
      this.record = record
      console.log(this.record)
      this.key1DataDetail=[]
      this.addDetailModel = true
      this.tableLoadingDetail = true
      //获得相关project device_id maintenance_type_id 拿 maintenance_project_id
      let device_id = record.device_id
      let maintenance_type_id = record.maintenance_type_id
      console.log("device_id maintenance_type_id",device_id,maintenance_type_id)

      await getDeviceMaintenanceTypeProjectRelationList({
        'device_id': device_id,
        'maintenance_type_id': maintenance_type_id
      }).then(async res => {
        if(res==='NoData' || res==='Error'){
          this.key1DataDetail=[]
          this.tableLoadingDetail = false
        }
        else{
          for (const it of res) {
            await getDeviceMaintenanceProjectList({'id':it.maintenance_project_id}).then(async res2 => {
              for (const it2 of res2) {
                it2['unit_name'] = await getCacheById(it2.unit_id)
                it2['real_value']=undefined
                it2['method']=''
                it2['info_real_cost_time'] = undefined
                it2['result'] = ''
                it2['device_id']=device_id
                it2['maintenance_type_id']=maintenance_type_id
                this.key1DataDetail.push(it2)
              }
            })
          }
        }

      })
      this.tableLoadingDetail = false
      console.log(this.key1DataDetail)
    },
    async delMaintenance() {
      // console.log(this.selectedRowKeys)
      for (const it of this.selectedRowKeys) {
        await deleteDeviceMaintenanceInfo({'id': it})
      }

      this.selectedRowKeys = []
      await this.initialize()
    },
    async filter() {
      //筛选
      this.pagination.page = 1
      this.pagination.current = 1
      this.pagination.page_size = 10
      this.tableLoading = true
      // 获取时间范围
      await this.initialize()
      const [startDate, endDate] = this.queryForm.dateSelect;
      // console.log(this.queryForm.dateSelect)
      // console.log(this.data)
      this.data = this.data.filter(item => {
        // 检查每个条件是否满足
        return (
            (this.queryForm.device_code ? item.device_code.includes(this.queryForm.device_code) : true) &&
            (this.queryForm.device_name ? item.device_name.includes(this.queryForm.device_name) : true) &&
            (this.queryForm.maintenance_status !== undefined ? item.maintenance_status === this.queryForm.maintenance_status : true) &&
            (this.queryForm.audit_status !== undefined ? item.status === this.queryForm.audit_status : true) &&
            (startDate ? new Date(item.create_time) >= new Date(startDate) : true) &&
            (endDate ? new Date(item.create_time) <= new Date(endDate) : true)
        );
      });
      this.tableLoading = false;
    },
    async initialize() {
      this.data=[]
      this.tableLoading = true
      const paramsAll = Object.assign({},{}, {
        "page": this.pagination.page,
        "page_size": this.pagination.page_size
      });

      await list_device_maintenance_info_all(paramsAll).then(async res => {
            if(res.data.code !== '1000'){
              this.tableLoading =false
              this.data=[]
            }else{
              this.pagination.total = res.data.extension.total+(this.pagination.current-1)*this.pagination.page_size
              for (const item of res.data.data) {
                //设备编码  设备名-device_id
                let searchDevice = await getDeviceList({'id': item.device_id})
                item['device_code'] = searchDevice[0]?.code || ''
                item['device_name'] = searchDevice[0]?.name || ''

                //保养日期 device_id  maintenance_type_id plan_id maintenance_plan_device_relation

                let searchMaintenance = await getMaintenancePlanDeviceRelationList({'device_id': item.device_id, 'maintenance_type_id': item.maintenance_type_id, 'plan_id': item.plan_id})

                item['maintenance_time'] = searchMaintenance[0].maintenance_time
                //保养完成日期 create_time

                //maintenance_type_id name
                item['maintenance_type_name'] = this.deviceMaintenanceTypeList.find(it=>it.id===item.maintenance_type_id)?.name || ''

                //保养状态 device_maintenance_task
                let searchTask = await listDeviceMaintenanceTaskAll({'device_id': item.device_id, 'maintenance_type_id': item.maintenance_type_id, 'plan_id': item.plan_id})
                item['maintenance_status'] = searchTask[0].status
                item['maintenance_status_name'] = this.taskStatusList.find(it=>it.code===item.maintenance_status)?.description || ''

                //保养人 plan_id device_id maintenance_type_id device_maintenance_task
                item['maintenance_person'] = searchTask[0].user_in_charge
                item['maintenance_person_name'] = await getUserNameById(searchTask[0].user_in_charge)

                //预计用时 maintenance_plan_device_relation expect_time
                item['expect_time'] = searchMaintenance[0].expect_time

                //实际用时 device_maintenance_task real_cost_time x info里的
                // item['real_cost_time'] = searchTask[0].real_cost_time
                //审核状态
                item['audit_status'] = this.taskAuditStatusList.find(it=>it.code===item.status)?.description || ''
                this.data.push(item)
              }

            }

      })
      this.tableLoading = false;
    },


    // 分页切换
    onChange (pagination) {
      this.pagination.current = pagination.current
      this.pagination.page_size = pagination.pageSize
      this.pagination.page = pagination.current
      this.getAssetLedgerList()
    },
    // 分页切换
    onChangeKey1 (pagination) {
      this.key1Pagination.current = pagination.current
      this.key1Pagination.page_size = pagination.pageSize
      this.key1Pagination.page = pagination.current
    },
    onChangeKey1Detail(pagination){
      this.key1DetailPagination.current = pagination.current
      this.key1DetailPagination.page_size = pagination.pageSize
      this.key1DetailPagination.page = pagination.current

    },
    async query() {
      this.tableLoading = true
      this.pagination.page = 1
      this.pagination.current = 0
      this.pagination.page_size = 10
      await this.initialize()
      this.tableLoading = false
    },
    reset() {
      this.queryForm = {
        device_code: '',
        device_name: '',
        maintenance_status:undefined,
        audit_status:undefined,
        dateSelect:[],
      }
      this.query()
    },
    async add() {
      this.addLoading=true
      this.addModal = true
      this.canBeEdited = true
      this.isAdd = true
      this.spinning = false
      //获取分配给自己的任务
      await this.getMyOrderTask()
      this.addLoading=false
    },
    async getMyOrderTask() {
      this.key1Data=[]
      let user = await getCurrentUserInfo()
      //user_id
      let user_id = user.user_id
      await listDeviceMaintenanceTaskByUserId({'user_id': user_id}).then(async res => {
        for (const item of res) {
          //设备编码 设备名称
          let searchDevice = await getDeviceList({'id': item.device_id})
          item['device_code'] = searchDevice[0]?.code || ''
          item['device_name'] = searchDevice[0]?.name || ''
          let searchMaintenance = await getMaintenancePlanDeviceRelationList({'plan_id': item.plan_id, 'device_id': item.device_id, 'maintenance_type_id': item.maintenance_type_id})
          item['maintenance_time'] = searchMaintenance[0].maintenance_time
          item['maintenance_type_name'] = this.deviceMaintenanceTypeList.find(it=>it.id===item.maintenance_type_id)?.name || ''
          item['maintenance_status'] = this.taskStatusList.find(it=>it.code===item.status)?.description || ''
          item['expect_time'] = searchMaintenance[0].expect_time

          this.key1Data.push(item)
        }
      })
      console.log(this.key1Data)
    },
    async edit(record) {
      this.getResult = {}
      this.getProject = {}
      this.editModal = true
      this.canBeEdited = true
      this.canBeQuery = true
      this.isAdd = true
      this.record = record
      // console.log(record)
      let searchProject = await getDeviceMaintenanceTypeProjectRelationList({
        'device_id': record.device_id,
        'maintenance_type_id': record.maintenance_type_id,
      })
      let getData = await getDeviceMaintenanceProjectList({'id': searchProject[0].maintenance_project_id})
      this.getProject = getData[0]
      // console.log(this.getProject)
      let getResult = await listDeviceMaintenanceResult({
        'task_id': record.task_id,
        'plan_id': record.plan_id,
        'device_id': record.device_id,
        'maintenance_project_id': searchProject[0].maintenance_project_id
      })
      this.getResult = getResult[0]
      // console.log(this.getResult)

    },
    del(id) {
      const params = Object.assign({},{'organization_id': storage.get(ORGANIZATION_ID),'asset_id': id})
      delete_asset(params)
          .then(res => {
            if (res && res.data.code && res.data.code === '1000') {
              this.getAssetLedgerList()
            } else {
              this.$message.error('删除失败',1)
            }
          })
          .catch(err => {
            console.log(err)
            this.$message.error('删除失败',1)
          })
    },
    async detail(record) {
      this.getResult={}
      this.getProject={}
      this.detailModal = true
      this.canBeEdited = false
      this.canBeQuery = true
      this.isAdd = false
      this.record = record
      // console.log(record)
      let searchProject = await getDeviceMaintenanceTypeProjectRelationList({
        'device_id': record.device_id,
        'maintenance_type_id': record.maintenance_type_id,
      })
      let getData = await getDeviceMaintenanceProjectList({'id': searchProject[0].maintenance_project_id})
      this.getProject= getData[0]
      // console.log(this.getProject)
      let getResult = await listDeviceMaintenanceResult({
        'task_id':record.task_id,
        'plan_id':record.plan_id,
        'device_id':record.device_id,
        'maintenance_project_id':searchProject[0].maintenance_project_id
      })
      this.getResult = getResult[0]
      // console.log(this.getResult)

    },
    detailCancel(){
      this.detailModal=false
    },
    remodel(record){
      this.remodelModal = true
      this.canBeEdited = false
      this.canBeQuery =true
      this.isAdd = false
      this.echo(record)
    },
    disposal(record){
      this.disposalModal = true
      this.canBeEdited = false
      this.canBeQuery =true
      this.isAdd = false
      this.echo(record)
    },
    clearParameter() {},
    handleCancel() {
      this.tabKey = '1'
    },
    handleCancel0() {
      this.addModal = false
      this.canBeEdited = false
      this.isAdd = false
    },
    handleCancelDetail(){
      this.addDetailModel = false

    },
    handleCancel1(){
      this.detailModal = false
      this.canBeEdited = false
      this.canBeQuery =false
      this.isAdd = false
    },
    handleCancel2(){
      this.disposalModal = false
      this.canBeEdited = false
      this.canBeQuery =false
      this.isAdd = false
    },
    submit() {

    },
  },
  beforeDestroy() {
    if (this.axiosSource) {
      this.axiosSource.cancel('Request canceled due to page navigation.');
    }
  }
}
</script>

<style scoped lang="less">

.dataBox{
  margin-top: 20px;
}

.hide-scrollbar::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}

::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}
.hide-scrollbar {
  -ms-overflow-style: none;  /* IE 和 Edge */
  scrollbar-width: none;  /* Firefox */
  overflow-y: scroll; /* 保持内容可滚动 */
}
.demo-infinite-container {
  margin-top: 0px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: auto;
  padding: 8px 24px;
  height: 300px;
}
/deep/ .ant-form-inline .ant-form-item-with-help{
  margin-bottom: 0px;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #f5f5f5;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .unit .ant-select-selection--single{
  margin-left: 0px;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-left: 0;
}
/deep/ .ant-select-disabled .ant-select-selection {
  background-color: #fff;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .ant-input-number-disabled{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
</style>